package vip.xiaonuo.bi.core.datasource.common.mysql;

import org.springframework.stereotype.Component;
import vip.xiaonuo.bi.core.datasource.common.AbstractDataSourceConfig;
import vip.xiaonuo.bi.core.datasource.common.client.AbstractRdbmsClient;
import vip.xiaonuo.bi.core.datasource.config.SqlQueryConig;
import vip.xiaonuo.bi.core.datasource.enums.DataSourceType;
import vip.xiaonuo.bi.core.datasource.factory.AbstractConectionFactory;
import vip.xiaonuo.bi.core.datasource.util.DButils;
import vip.xiaonuo.common.exception.CommonException;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 *  mysql关系型数据库具体操作
 *  @author 顾育司
 *  @date  2023/12/15 12:09
 */
@Component
public class MysqlClient extends AbstractRdbmsClient {
    private  final  static String queryColonmComent = "show full columns from %s;"; // 替换表名即可
    @Override
    public String getType() {
        return DataSourceType.MySQL.getVal()+"";
    }


    @Override
    protected AbstractConectionFactory getConectionFactory() {
        return new MysqlConectionFactory();
    }


    protected Map<String, String> getColumnComments(AbstractDataSourceConfig dataSourceConfig, SqlQueryConig queryConig) {
       // 定义结果集
        Map<String, String> result = new HashMap<>();

        // 获取表名的sql
        String queryColonmComentSql = String.format(queryColonmComent, queryConig.getTable());
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {

            // 获取执行sql语句  select * from table where 1=2;
            String queryColumnSql = DButils.getQueryColumnSql(queryConig.getTable());
            // 获取元数据信息
            connection = getConnection(dataSourceConfig);
            // 获取预编译
            statement = connection.createStatement();
            // 获取执行sql
            rs = statement.executeQuery(queryColonmComentSql);
            while (rs.next()) {
                String columnName = rs.getString("Field");
                String columnComment = rs.getString("Comment");
                result.put(columnName, columnComment);
            }
            return result;
        }catch (Exception e){
             throw  new CommonException("获取表字段注释失败，没有该表："+queryConig.getTable());

        }finally {
            connectionFactory.close(connection, statement, rs);
        }
    }
}
